package com.lovegu.thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 老顾
 * @title: MyThreadFactory
 * @projectName java-restudy
 * @email: 1437594522@qq.com
 * @date 2022/9/23 15:45
 */
public class MyThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private String namePrefix;
    MyThreadFactory(String name) {
        SecurityManager s = System.getSecurityManager();
//        group = (s != null) ? s.getThreadGroup();
        Thread.currentThread().getThreadGroup();
        namePrefix = name + "-" + poolNumber.getAndIncrement() +"-thread-";
    }

    MyThreadFactory(ThreadGroup group, String namePrefix){
        this("default");
    }
    public Thread newThread(Runnable r) {
        // 就是在创建线程
        Thread t = new Thread(group, r,namePrefix +threadNumber.getAndIncrement(), 0);
        if (t.isDaemon())
            t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}
